
//
//  ZYComposeViewController.swift
//  WBBeta1
//
//  Created by wustzhy on 16/8/17.
//  Copyright © 2016年 Yestin. All rights reserved.
//

import UIKit
import SVProgressHUD

class ZYComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }

    func setupUI(){
        view.backgroundColor = UIColor.whiteColor()
        setupNav()
        view.addSubview(composeTextView)
        view.addSubview(bottomBarView)
        composeTextView.addSubview(pictureView)//注意！！！//可随着textview滚动而动
        
        composeTextView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        }
        bottomBarView.snp_makeConstraints { (make) -> Void in
            make.leading.bottom.trailing.equalTo(view)
            make.height.equalTo(44)
        }
        pictureView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(composeTextView).offset(100)
            make.size.equalTo(CGSize(width: SCREENW-20, height: SCREENW-20))
            make.centerX.equalTo(composeTextView)
        }
        
        
        //底部按钮点击 闭包实例化
        bottomBarView.closureOfButton = {[weak self] (type:childButtonType) -> () in
            switch type{
            case .Picture:
                printLog("图")
                self?.selectImage()
            case .Mention:
                printLog("@")
            case .Trend:
                printLog("#")
            case .Emoticon:
                printLog("笑脸")
                self?.switchKeyboard()
            case .Add:
                printLog("+")
            }

        }
        pictureView.closureSelectCell = { [weak self] in
//            printLog("cell点击了,去相册选图")
            self?.selectImage()
        }
        
        //注册系统通知 --监听键盘
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    func keyboardChange(noti:NSNotification) {
        //动画时长
        guard let duration = noti.userInfo?["UIKeyboardAnimationDurationUserInfoKey"] as? Double else{
            return
        }
        //判断是否为nil，并可否转为NSValue
        guard let rect = noti.userInfo?["UIKeyboardFrameEndUserInfoKey"] as? NSValue else {
            return
        }
        //转成CGRect
        let newRect = rect.CGRectValue()
        //更新约束
        bottomBarView.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(newRect.origin.y - SCREENH)
        }
        //设置动画
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    func setupNav(){
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: "sendAction")
        navigationItem.rightBarButtonItem?.enabled = false
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelAction")
        //titleView
        navigationItem.titleView = titleView
    }
    @objc private func sendAction(){
        printLog("发布")
        pictureView.imageList.count == 0 ? update() : upload()
        
    }
    @objc private func cancelAction(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    private lazy var titleView: UILabel = {

        let name = ZYUserAccountViewModel.sharedTools.userAccount!.screen_name!
        let str = "发微博\n\(name)"
        //富文本
        let attr = NSMutableAttributedString(string: str)
        let range = (str as NSString).rangeOfString(name)
        //设置 富文本
        attr.addAttributes([NSForegroundColorAttributeName:AppThemeColor,NSFontAttributeName:UIFont.systemFontOfSize(12)], range: range)
        
        let lab = UILabel()
        lab.attributedText = attr
        lab.numberOfLines = 0
        lab.textAlignment = .Center
        lab.sizeToFit()// 设置size，不然不显示
        return lab
    }()
    
    private lazy var composeTextView: ZYComposeTextView = {
       let view = ZYComposeTextView()
        view.delegate = self
        //设 字体，setter
        view.font = UIFont.systemFontOfSize(16)
        //设 占位文字
        view.placeholder = "who are you, please do something here"
        //允许上下滚动
        view.alwaysBounceVertical = true
        // default NO. if YES and bounces is YES, even if content is smaller than bounds, allow drag vertically
        return view
    }()
    
    private lazy var bottomBarView:ZYComposeBottomView = ZYComposeBottomView()
    private lazy var pictureView:ZYComposePictureView = ZYComposePictureView()
    private lazy var emoticonKeyboardView:ZYEmoticonKeyboardView = ZYEmoticonKeyboardView(frame: CGRect(x: 0, y: 0, width: SCREENW, height: 216))
}

extension ZYComposeViewController:UITextViewDelegate{
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = composeTextView.hasText()
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        //取消键盘的第一相应---消失
        composeTextView.resignFirstResponder()
    }
}

//MARK: -处理bottomView的按钮点击事件
extension ZYComposeViewController {
    func selectImage(){
        let imagePickerVc = UIImagePickerController()
        imagePickerVc.delegate = self
        self.presentViewController(imagePickerVc, animated: true, completion: nil)
    }
    func switchKeyboard() {
        //if系统键盘
        if composeTextView.inputView == nil {
            composeTextView.inputView = emoticonKeyboardView
            bottomBarView.isEmoticon = true
        }else{
            //if表情键盘
            composeTextView.inputView = nil
            bottomBarView.isEmoticon = false
        }
        // 刷新
        composeTextView.reloadInputViews()
        composeTextView.becomeFirstResponder()
    }
}

extension ZYComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        let image = info["UIImagePickerControllerOriginalImage"] as! UIImage
        //选图 传图给collectionCell  //压缩后传
        pictureView.addImage(UIImage.dealImageScale(image, width: 600))
        //关闭 相册
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        picker.dismissViewControllerAnimated(true, completion: nil)
    }

}

//MARK: - 发布wb 请求
extension ZYComposeViewController {
    
    func update() {
        ZYNetworkTools.sharedTools.composeUpdate(composeTextView.text, success: { (response) -> () in
            SVProgressHUD.showSuccessWithStatus("发布成功")
            }) { (error) -> () in
                SVProgressHUD.showErrorWithStatus("发布失败")
        }
    }
    
    func upload() {
        ZYNetworkTools.sharedTools.composeUpload(composeTextView.text, images: pictureView.imageList, success: { (response) -> () in
            SVProgressHUD.showSuccessWithStatus("发布成功")
            }) { (error) -> () in
                SVProgressHUD.showErrorWithStatus("发布失败")
        }
    }
    
}













